import Request from './request'

const url = '/api/auth/coins'
export default {
  cache: {
    incCoins: {},
    setCoins: {},
    getCoins: {},
  },
  getCoins() {
    return Request.get(url)
  },
  setCoins(total) {
    return Request.post(url, { total })
  },
  incCoins(inc) {
    let now = Date.now()
    let last = this.cache.incCoins.last
    if (!this.cache.incCoins.last) {
      last = this.cache.incCoins.last = now
    }

    let actions = null
    if (!this.cache.incCoins.actions) {
      this.cache.incCoins.actions = []
    }

    actions = this.cache.incCoins.actions
    
    actions.push({
      t: 'inc',
      v: inc,
    })

    // 距离上次提交已经过了10s
    if ((now - last) > (10 * 1000)) {
      this.cache.incCoins.last = now
      let data = actions.slice(0)
      this.cache.incCoins.actions = []
      if (data.length) {
        return Request.post(url, {actions: data})
      } else {
        return Promise.resolve('EMPTY ACTIONS')
      }
    } else {
      return Promise.resolve('CACHED')
    }

  }
}